package cn.afterturn.oneopen.filter;

import cn.afterturn.oneopen.model.OrgInfoModel;
import cn.afterturn.oneopen.service.IOrgInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * 签名拦截器
 * 和天眼查保持一致,只校验header的token
 *
 * @author by jueyue on 19-3-9.
 */
@Component
public class SignFilter implements GlobalFilter, Ordered {

    private static final Logger LOGGER = LoggerFactory.getLogger(SignFilter.class);

    @Autowired
    private IOrgInfoService orgInfoService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        OrgInfoModel model = null;
        try {
            String token = exchange.getRequest().getHeaders().get("token").get(0);
            model = orgInfoService.getOne(new QueryWrapper<OrgInfoModel>().eq("token", token));
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        if (model == null) {
            // 该用户不存在
            byte[]     bytes  = "{\"status\":\"-99\",\"msg\":\"用户不存在\"}".getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
            return exchange.getResponse().writeWith(Flux.just(buffer));
        } else if (model.getBalance() < 10) {
            // 余额不足
            byte[]     bytes  = "{\"status\":\"-1\",\"msg\":\"余额不足\"}".getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
            return exchange.getResponse().writeWith(Flux.just(buffer));
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
